package util;


import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class JSONUtils {
	public static <T> T json2Bean(String result, Class<T> clz) {
		Gson gson = new Gson();
		T t = gson.fromJson(result, clz);
		return t;
	}

    public static Map<String,String> jsonObject2Map(JSONObject jsonObj)
    {
        Map<String,String> retMap = new HashMap<String, String>();
        Iterator keyit = jsonObj.keys();
        while(keyit.hasNext()){
            String key = (String)keyit.next();
            retMap.put(key, jsonObj.optString(key));
        }
        return retMap;
    }

    public static JSONObject addJSONParam( JSONObject reqJSON,String name ,String value){
        try {
            reqJSON.put(name, value);
            return reqJSON;
        }catch(JSONException ex){
            throw new RuntimeException(ex);
        }
    }
    public static JSONObject addJSONParam( JSONObject reqJSON,String name ,int value){
        try {
            reqJSON.put(name, value);
            return reqJSON;
        }catch(JSONException ex){
            throw new RuntimeException(ex);
        }
    }
    public static JSONObject addJSONParam( JSONObject reqJSON,String name ,JSONObject value){
        try {
            reqJSON.put(name, value);
            return reqJSON;
        }catch(JSONException ex){
            throw new RuntimeException(ex);
        }
    }

    public static JSONObject addJSONParam( JSONObject reqJSON,String name ,JSONArray value){
        try {
            reqJSON.put(name, value);
            return reqJSON;
        }catch(JSONException ex){
            throw new RuntimeException(ex);
        }
    }
}
